"""
This script will try to see what the connection is between some severe faults and the SCADA data leading uptill that fault.
This will then be used to generate patterens that can tell something about the fault. Thus using this pattern to detect and isolate faults.
"""

import sys
sys.path.append("../reading_data")

import logging
from logging import debug
logging.basicConfig(format='%(levelname)s:%(message)s', level=logging.DEBUG)

import cPickle as pickle
import datetime
from matplotlib.dates import num2date
from matplotlib.dates import date2num

import matplotlib.pyplot as plt


from read_from_h5 import load_data

def get_data(turbine, time):
    turbid = turbine.upper()
    start_time = num2date(time) + datetime.timedelta(200)
    prev_time = start_time - datetime.timedelta(300)
    h5_file = "../../bindata/data.h5"
    filt_strings = ["(activepoweravg > 0)",
                    "(activepoweravg < 2200)",
                    "(time >= " + str(date2num(prev_time)) + " )",
                    #"(time <= " + str(date2num(start_time)) + " )"]
                    "(time <= " + str(date2num(start_time)) + " )",
                    "(turbid == '" + turbid + "' )"]
    debug(filt_strings)

    data = load_data(h5_file, filt=filt_strings)
    return data

def main():
    p_file = open("../../bindata/severe_faults.pickle", 'rb')
    severe_faults = pickle.load(p_file)
    p_file.close()
    print severe_faults.keys()
    gear_changes = severe_faults[30]
    turbid = gear_changes[0][0]
    time = gear_changes[0][1]
    print num2date(time)
    data = get_data(turbid, time)
    fig, ax = plt.subplots(1, 1)
    ax.plot(num2date(data["time"]), data["gearoiltempavg"], 'o')
    fig.autofmt_xdate()
    plt.show()


if __name__=='__main__':
    main()
